//
//  LWJBaseRequest.m
//  HengYouCai
//
//  Created by ycgwl on 2017/5/11.
//  Copyright © 2017年 lwj. All rights reserved.
//

#import "LWJBaseRequest.h"
#import <AFNetworking/AFNetworking.h>
//#import "WLHttpServiceStatus.h"
//#import "WLFileManager.h"
//#import "SHNetService.h"
#import "WLTool.h"

@implementation LWJBaseRequest


+ (void)doHttpWithUrl:(NSString *)url andMetohd:(NSString *)method andParameters:(NSDictionary *)parameters andHeaders:(NSDictionary *)headers withSuccessHandler:(successHandler)successHandler andFailHandler:(failHandler)failHandler{
    
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        failHandler(nil,-200,@"请检查您的网络");
        return;
    }
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
    [manager setResponseSerializer:responseSerializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //设置请求超时时间20秒
    manager.requestSerializer.timeoutInterval = 20;
    for (NSString*key in headers) {
        [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
    }
    //用户token
    NSString *userToken = [WLFileManager readUserDataForKey:kUserSessionId];
    if (userToken!=nil) {
        [manager.requestSerializer setValue:userToken forHTTPHeaderField:kUserSessionId];
    }
    //渠道码
    [manager.requestSerializer setValue:kChannel_app forHTTPHeaderField:@"appChannel"];
    //来源
    [manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"OSType"];
    //设备号
    [manager.requestSerializer setValue:[WLTool getAppDeviceUdid] forHTTPHeaderField:@"uniqueIdentifier"];
    //IDFA 唯一标志
    [manager.requestSerializer setValue:[WLTool getAppIDFA] forHTTPHeaderField:@"idfaIdentifier"];
    //手机型号
    [manager.requestSerializer setValue:[NSObject wl_getDeviceModel] forHTTPHeaderField:@"deviceModel"];
    //手机系统版本
    [manager.requestSerializer setValue:[[UIDevice currentDevice] systemVersion] forHTTPHeaderField:@"OSVersion"];
    //应用程序版本
    NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [dict objectForKey:@"CFBundleShortVersionString"];
    [manager.requestSerializer setValue:app_Version forHTTPHeaderField:@"appVersion"];
    
    ///防止重复取出token传递出去唯一性 非空 请求头和参数各放一份
    NSString * jcwToken = [WLFileManager readUserDataForKey:@"jcwToken2018328"];
    if (jcwToken.length) {
        [manager.requestSerializer setValue:jcwToken forHTTPHeaderField:@"token"];
        NSMutableDictionary * temp = [NSMutableDictionary dictionaryWithDictionary:parameters];
        [temp setObject:jcwToken forKey:@"token"];
        parameters = temp;
    }
    
    [manager.requestSerializer requestWithMethod:[method uppercaseString] URLString:url parameters:parameters error:nil];
    void(^af_success_cb)() = ^(NSHTTPURLResponse *response, id responseObject) {
        successHandler(responseObject,response.statusCode);
        ///请求头中
        NSString * jcwToken = response.allHeaderFields[@"token"];
        if (jcwToken.length) {
            [WLFileManager saveUserData:jcwToken forKey:@"jcwToken2018328"];
        }
        ///参数中
        NSDictionary * dic = (NSDictionary *)responseObject;
        NSDictionary * dic1 = (NSDictionary *)dic[@"result"];
        NSString * jcwParamToken = dic1[@"token"];
        if (jcwParamToken.length) {
            [WLFileManager saveUserData:jcwParamToken forKey:@"jcwToken2018328"];
        }
    };
    void(^af_error_cb)(NSHTTPURLResponse *response, NSError *error) = ^(NSHTTPURLResponse *response, NSError *error) {
        NSString *strErrorMsg;
        ///防止重复提交 保存token值  之后传递出去唯一性 非空  因为提现可能出现多次
        NSString * jcwToken = response.allHeaderFields[@"token"];
        if (jcwToken.length) {
            [WLFileManager saveUserData:jcwToken forKey:@"jcwToken2018328"];
        }
        if (response.statusCode == 401) {
            
//            [HYCNetService loginWithDict:nil onSuccess:^(NSDictionary *dictResult) {
//                //
//                
//            } andFailed:^(NSInteger code, NSString *errorMsg) {
//                //
//            }];
            strErrorMsg = @"您的账号在别处登录,请重新登录";
                //
            [WLFileManager removeUserDataForkey:kUserSessionId];
            
//            [WLFileManager removeUserDataForkey:kUserAccount];
            [WLFileManager removeUserDataForkey:kCusCode];
            [WLFileManager removeUserDataForkey:kCardStatus];
            [WLFileManager removeUserDataForkey:kUserIdCard];
            [WLFileManager removeUserDataForkey:kUserRealname];
            [WLFileManager removeUserDataForkey:kUserPaypassword];
            [WLFileManager removeUserDataForkey:kRealnameStatus];
            [WLFileManager removeUserDataForkey:KWalletaward];
            [WLFileManager removeUserDataForkey:kUserLevel];

                
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationNeedLogin object:nil];

            
        }else if (response.statusCode/100 == 5){
            strErrorMsg = @"正在处理中，请稍后...";
                        NSLog(@"%@--%zd----%@",url,response.statusCode,strErrorMsg);
        }else if (response.statusCode/100 == 3){
            strErrorMsg = @"服务器跳转中...";
        }else{
            strErrorMsg = @"正在处理中，请稍后...";
                        NSLog(@"%@--%zd----%@",url,response.statusCode,strErrorMsg);
        }
        failHandler(error,response.statusCode,strErrorMsg);
    };
    
    if ([[method lowercaseString] isEqualToString:@"get"]) {
        NSLog(@"当前url = %@",url);
        [manager GET:url parameters:parameters progress:^(NSProgress *downloadProgress) {
            
        } success:^(NSURLSessionDataTask *task, id responseObject) {
            af_success_cb((NSHTTPURLResponse*)task.response,responseObject);
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            af_error_cb((NSHTTPURLResponse*)task.response,error);
        }];
    }else if([[method lowercaseString] isEqual:@"post"]) {
         NSLog(@"当前url = %@",url);
        [manager POST:url parameters:parameters progress:^(NSProgress *uploadProgress) {
            
        } success:^(NSURLSessionDataTask *task, id responseObject) {
            af_success_cb((NSHTTPURLResponse*)task.response,responseObject);
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            af_error_cb((NSHTTPURLResponse*)task.response,error);
        }];
    }
}

@end
